<template>
	<view>
		<!-- 将顶部导航栏吸顶 -->
		<u-sticky>
			<u-subsection :list="orderList" :current="currentOrderType" @change="sectionChange"></u-subsection>
		</u-sticky>
		<!-- v-if渲染订单查询到的订单 -->
		<!-- 0待付款 1待出行 2进行中 3已完成 4取消中 5已取消 6退款中 7已退款 -->
		<!-- v-for循环渲染 -->

		<view class="orderContain">
			<uni-card :title="item.activityName" :extra="'￥'+item.amount" v-for="(item,index) in userOrders"
				:key="index" @click="toOrderDetail(item)">
				<view class="orderMain">
					<view class="orderAvatar">
						<u-avatar size='60' :src='item.image.imgSrc'></u-avatar>
					</view>
					<view class="orderRight">
						<view class="orderNum u-line-1">
							订单名称：{{item.activityName}}
						</view>
						<view class="orderCon">
							订单状态：{{tipList[item.status]}}
						</view>
					</view>
					<view class="odrersBtn">
						<view class="odrersBtn1">
							<u-button color="#62d8d6" throttleTime='1000' :text="btnList[item.status][0]"
								@click="toOrderDetail(item)"></u-button>
						</view>
						<view class="odrersBtn2">
							<u-button color="#62d8d6" throttleTime='1000' :text="btnList[item.status][1]"
								@click.native.stop="cancelOrder(item)"></u-button>
						</view>
					</view>

				</view>

			</uni-card>
		</view>


		<!-- v-else，如果没查到，显示此界面 -->
		<u-empty v-if="userOrders.length==0" mode="order" icon="http://cdn.uviewui.com/uview/empty/order.png">
		</u-empty>

		<!-- 遮罩层 -->
		<u-overlay :show="toLodingOrder" mask-click-able="false">
			<u-loading-icon text="加载中" textSize="18"></u-loading-icon>
		</u-overlay>

		<!-- 取消订单，退款弹窗 -->
		<view>
			<u-popup :show="show" mode="center" @close="close" round="20" customStyle="width:450rpx; height:350rpx">
				<view class="bottomPay">
					<view>我想您一定是深思熟虑</view>
					<view>我们还需再改进</view>
					<view class="example-body">
						<uni-combox :candidates="candidates" placeholder="请选择取消/退款原因" v-model="reason"></uni-combox>
					</view>
					<view @click="returnPay" class="returnPay">
						<text>确认</text>
					</view>
				</view>
			</u-popup>
		</view>
		<view class="popup" v-show="canclePopup">
			<u-loading-icon></u-loading-icon>
			<view>取消订单中...</view>
		</view>



	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		onLoad: async function(orderType) {
			this.currentOrderType = orderType.orderType
			//根据currentOrderType订单状态查询相同状态的订单数据
		},
		onReachBottom: function() {
			if (this.userOrderQuery.page * this.userOrderQuery.pageSize >= this.totalNum) {
				return uni.showToast({
					title: "数据已经到底了",
					icon: 'error'
				})
			} else {
				this.userOrderQuery.page += 1;
				this.getUserOrder()
			}

		},
		computed: {
			...mapState('messageArray', ['messageArray']),
		},
		data() {
			return {
				//btnList和orderList一一对应
				btnList: [
					['去付款', '取消订单'],
					['查看订单', '申请退款'],
					['查看订单', '申请退款'],
					['去评价', '申请退款'],
					['重新下单', '取消中'],
					['重新下单', '已取消'],
					['重新下单', '退款中'],
					['重新下单', '已退款'],
				],
				orderList: ['待付款', '待出行', '进行中', '已结束', '全部订单'],
				tipList:['待付款', '待出行', '进行中', '已结束', '取消中','已取消','退款中','已退款'],
				currentOrderType: null,
				userOrders: [],
				userOrderQuery: {
					page: 1,
					pageSize: 5, //一次展示五个收藏
					status: null
				},
				show: false,
				totalNum: 0,
				toLodingOrder: false,
				slipFlag: false,
				reason: '',
				canclePopup: false,
				startPoint: 0,
				cancelOrderId: -1,
				candidates: ['不想要了', '想重新下单', '地点有变', '不想去了', '时间冲突了', '选错了'],
				refreshFlag:false//页面刷新标志
			}
		},
		methods: {
			close() {
				this.reason=''
				this.show = false
			},
			sectionChange(index) {
				this.currentOrderType = index
			},
			cancelOrder(item) {
				if(item.status==5 || item.status == 4 || item.status== 6 || item.status==7){
					return uni.showToast({
						title:'请勿重复点击',
						icon:'error'
					})
				}else{
					this.show = true
					this.cancelOrderId = item.id
				}
				
			},
			// 取消订单,退款方法
			async returnPay() {
				if (this.reason !== '') {
					this.canclePopup = true
					const res = await uni.$u.http.post("/user/order/userCancel", {
						cancelReason: this.reason,
						id: this.cancelOrderId
					}, {
						custom: {
							auth: true
						}
					}).then(result => {
						if (result.data.code === 1) {
							this.refreshFlag=!this.refreshFlag
							this.canclePopup=false
							this.show=false
							uni.showToast({
								title: '取消/退款成功',
								icon: 'success',
								duration: 1000
							})
						}
					})
				} else {
					this.show=false
					return uni.showToast({
						title: '请选择退款原因',
						icon: 'error'
					})
				}
			},
			async toOrderDetail(item) {
				// 下单时间 item.orderTime，将下单时间换为时间戳 
				//部分ios不支持yyyy-MM-dd格式的时间所以需要转换
				item.orderTime = item.orderTime.replace(/-/g, '/');
				let time = new Date(item.orderTime);
				//获取当前时间
				let nowTime=Date.now()
				// 订单过期了，删除订单
				if(time.getTime()+15*60*1000<nowTime && item.status==0){
					 uni.showToast({
					 	title:"订单过期了",
					 	icon:'error'
					 })
					const res = await uni.$u.http.post("/user/order/userCancel", {
						cancelReason: "订单过期",
						id: item.id
					}, {
						custom: {
							auth: true
						}
					}).then(result => {
						if (result.data.code === 1) {
							this.refreshFlag=!this.refreshFlag
						}
					})
				}else if(item.status==0){
					//去支付界面
					uni.navigateTo({
						url: '/subpkg/orderOperating/toPayFor?orderAmount=' + item.amount + '&orderTime=' + item.orderTime + '&orderNumber=' + item.number
					})
					
				}else if(item.status==1||item.status==2){
					// 订单详情页面 传递订单id方便查询
					uni.navigateTo({
						url:'/subpkg/orderDetail/orderDetail?orderId='+item.id+'&currentOrderType='+this.currentOrderType
					})
				}else if(item.status==3||item.status==4){
					// 评论界面
					uni.navigateTo({
						url:'/subpkg/orderComment/orderComment?orderId=' + item.id+ '&activityId=' + item.activityId
					})
				}else{
					//去下单界面
					uni.navigateTo({
						url: '/subpkg/detailLine/detailLine?activityId=' + item.activityId
					})
				}
				
				
			},
			async getUserOrder() {
				this.toLodingOrder = true
				await uni.$u.http.get('/user/order/historyOrders', {
					params: this.userOrderQuery,
					custom: {
						auth: true
					}
				}).then(res => {
					this.totalNum = res.data.data.total
					this.userOrders = [...this.userOrders, ...res.data.data.records]
				}).catch(() => {
					return uni.showToast({
						title: "请求错误",
						icon: 'error'
					})
				}).finally(() => {
					this.toLodingOrder = false
				})


			}
		},
		watch: {
			// 侦听currentOrderType的值的变化，如果有变就进行查询， 第一次进来也会查询
			currentOrderType: {
				handler(newValue, oldValue) {
					if (newValue == 4) {
						this.userOrderQuery.status = null
					} else {
						this.userOrderQuery.status = newValue
					}
					this.userOrderQuery.page = 1 //currentOrderType变化时,初始的页数为1
					this.userOrders = [] //currentOrderType变化的时候清空userOrders
					this.getUserOrder()
				}
			},
			refreshFlag:{
				handler(newValue, oldValue) {
					this.userOrderQuery.page = 1 //currentOrderType变化时,初始的页数为1
					this.userOrders = [] //currentOrderType变化的时候清空userOrders
					this.getUserOrder()
				}
			}



		},
	}
</script>

<style lang="scss" scoped>
	.orderMain {
		display: flex;
		flex-direction: row;
		justify-content: space-around;

		.orderAvatar {
			display: flex;
			align-items: center;
		}

		.orderRight {
			display: flex;
			justify-content: space-around;
			flex-direction: column;
		}

		.odrersBtn {
			padding-left: 20rpx;
			display: flex;
			align-items: center;
			flex-direction: column;
			justify-content: space-around;

			.odrersBtn1 {
				margin-bottom: 10rpx;
			}
		}
	}

	.returnPay {
		display: flex;
		flex-direction: column;
		width: 120rpx;
		height: 50rpx;
		border-radius: 20rpx;
		background-color: aqua;
		align-items: center;
		justify-content: center;
		margin-top: 40rpx;
	}

	.bottomPay {
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		line-height: 70rpx;
	}
</style>